import { TComponent } from '@material/typeing';
import { FC, ReactNode, useEffect, useMemo, useRef, useState } from 'react';
import $style from './index.scss';
import { isFunction } from '@material/helpers';
import { getStyleHeight } from '@/utils/dom';
export interface ExpandablePanelProps extends TComponent {
    isExpanded?: boolean;
    disabled?: boolean;
    header: ReactNode;
    onToggle?: (e: React.MouseEvent<Element, MouseEvent>) => void;
}

const ExpandablePanel: FC<ExpandablePanelProps> = function (props) {
    const { className, disabled, header, style, children, onToggle, isExpanded } = props;
    const contentRef = useRef<HTMLDivElement>(null);
    const [height, setHeight] = useState<string | number>(0);
    const updateStyle = useMemo(() => {
        if (height) {
            return {
                height: typeof height === 'number' ? `${height}px` : 'auto'
            };
        }
        return {
            height: 0
        };
    }, [height]);
    useEffect(() => {
        if (!contentRef.current) {
            return;
        }
        console.log(contentRef.current.offsetHeight);
        if (!isExpanded) {
            const height = getStyleHeight(contentRef.current);
            contentRef.current.style.height = `${height}px`;
            setHeight(0);
            return;
        }

        contentRef.current.style.height = 'auto';
        const height = getStyleHeight(contentRef.current);
        contentRef.current.style.height = `${0}px`;
        setHeight(height);
    }, [isExpanded]);
    const clickEventHandler = (e: React.MouseEvent<Element, MouseEvent>) => {
        if (disabled) return;
        isFunction(onToggle) && onToggle(e);
        e.stopPropagation();
    };
    return (
        <div className={[$style['expandable-panel'], className]}>
            <div
                className={$style.header}
                onClick={clickEventHandler}
            >
                {header}
            </div>
            <div
                ref={contentRef}
                className={$style.panel}
                style={{ ...style, ...updateStyle }}
            >
                {children}
            </div>
        </div>
    );
};

export default ExpandablePanel;
